package com.ljx.recruitment.user.service.impl.email;

import cn.hutool.core.util.RandomUtil;
import com.ljx.recruitment.common.exception.ApiException;
import com.ljx.recruitment.interview.constant.JobConstant;
import com.ljx.recruitment.interview.enums.DeliverOptionEnum;
import com.ljx.recruitment.interview.enums.JobBaseProcessEnum;
import com.ljx.recruitment.user.domain.vo.req.EmailSendReq;
import com.ljx.recruitment.user.domain.vo.resp.EmailSendResp;
import com.ljx.recruitment.user.service.EmailSendService;
import com.ljx.recruitment.user.util.EmailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-11-06  22:16
 */
@Slf4j
public class WrittenExaminationEmailSendServiceImpl implements EmailSendService {
    @Override
    public EmailSendResp sendEmail(JavaMailSender mailSender, EmailSendReq req) {
        String requestId = RandomUtil.randomString(10);
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(req.getFrom());
            helper.setTo(req.getTo());
            helper.setSubject(getTitle(req.getDetailsMap()));
            helper.setText(getContent(req.getDetailsMap()), true);
            mailSender.send(message);
        } catch (Exception e){
            log.error("发送笔试邮件出错，{}", e.getMessage());
            throw new ApiException("发送笔试邮件出错");
        }

        return EmailSendResp.builder()
                .email(req.getTo())
                .requestId(requestId)
                .build();
    }

    @Override
    public String getTitle(Map<String, String> params) {
        return EmailUtil.getTitleDetail(params).getOldTitle() + "通知";
    }

    @Override
    public String getContent(Map<String, String> params) {
        Integer nextDeliverStatus = Integer.valueOf(params.get(JobConstant.NEXT_DELIVER_STATUS));
        Integer option = Integer.parseInt(params.get("option"));
        if (DeliverOptionEnum.PASS.getKey().equals(option)) {
            if (JobBaseProcessEnum.WRITTEN_EXAMINATION.getKey().equals(nextDeliverStatus)) {
                return EmailUtil.getWrittenContent(params);
            } else if (JobBaseProcessEnum.MAJOR_INTERVIEW.getKey().equals(nextDeliverStatus)) {
                return EmailUtil.getInterviewContent(params);
            } else if (JobBaseProcessEnum.HR_INTERVIEW.getKey().equals(nextDeliverStatus)) {
                return EmailUtil.getInterviewContent(params);
            } else if (JobBaseProcessEnum.OFFER.getKey().equals(nextDeliverStatus)) {
                return EmailUtil.getWaitOfferContent(params);
            } else {
                return "错误邮件，请联系管理员";
            }
        }
        return EmailUtil.getThanksContent(params);
    }

}
